/*
 * 更新出库表
 * 参数   交易码：trancode=51216
 * 
 */

package org.ccams.tran;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.ccams.domain.TMaterielStock;
import org.ccams.domain.TpOutDetail;
import org.ccams.domain.TpOutHead;
import org.ccams.web.WebBeanFactory;
import org.json.JSONArray;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;


public class Tran51216 extends AbstractJsonTran {

	@SuppressWarnings("unchecked")
	public void buildJSONObject(Map model, JSONObject json,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		Long numId =Long.parseLong( request.getParameter("numId"));//取得记录ID
		// 获得用户录入信息
		Date operdate = new SimpleDateFormat("y-M-d").parse((String) request.getParameter("operdate"));
		System.out.println("验收日期:"+operdate);
		String prov_name=(String) request.getParameter("prov_name");
		System.out.println("供应商:"+prov_name);
		Date cw_Date = new Date();
		String cw_date = request.getParameter("cw_date");
		if(!("".equals(cw_date)))
		{
			cw_Date=new SimpleDateFormat("y-M-d").parse(cw_date);
			System.out.println("财务日期:"+cw_Date);
		}
		
		String out_no=(String) request.getParameter("out_no");
		System.out.println("单据编号:"+out_no);
		String tran_kind = (String) request.getParameter("tran_kind");
		Short tranKind;
		if(tran_kind.equals("供应商自付")){
			tranKind = 0;
		}else if(tran_kind.equals("我方垫付")){
			tranKind = 1;
		}else{
			tranKind = Short.parseShort(tran_kind);
		}
		
		System.out.println("支付方式:"+tran_kind);
		Double tran_money= Double.parseDouble((String) request.getParameter("tran_money"));
		System.out.println("运费:"+tran_money);
		String uname = (String) request.getParameter("uname");
		System.out.println("进货部门:"+uname);
		String operName = (String) request.getParameter("operName");		
		System.out.println("验收人:"+operName);
		String operUName = (String) request.getParameter("operUName");
		System.out.println("验收人部门:"+operUName);
		String remark = (String) request.getParameter("remark");
		System.out.println("备注:"+remark);
		
		
		TpOutHead toh = new TpOutHead();
		toh.setNum(numId);
		toh.setProv_name(prov_name);
		toh.setCw_date(cw_Date);
		toh.setOut_no(out_no);
		toh.setTran_kind(tranKind); 
		toh.setTran_money(tran_money);
		toh.setUname(uname);
		toh.setOperdate(operdate);
		toh.setOperName(operName);
		toh.setOperUName(operUName);
		toh.setRemark(remark);
		
		//获得详细信息
		String params = (String) request.getParameter("detail");
		
		JSONArray detailParams = new JSONArray(params);
		
		HashMap<String, Object> jsonMap = new HashMap<String, Object>();
		String success = "";
		String message = "";	
		int k=0;		
		DataSourceTransactionManager txm = (DataSourceTransactionManager) WebBeanFactory.getBean("transactionManager",request);
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txm.getTransaction(def);
		try{  
			k = getCcamsService().getTpoutheadDao().updateTpouthead(toh);//添加入库主表信息
			for(int i=0;i<detailParams.length();i++){
				org.json.JSONObject detail = detailParams.optJSONObject(i);
				TpOutDetail tod = new TpOutDetail();
				tod.setNum(numId);
				tod.setIdt_Materiel(detail.getLong("idt_materiel"));
				tod.setMaterielName(detail.getString("materielName"));
				tod.setBatchno(detail.getString("batchno"));
				tod.setKind(Short.parseShort(detail.getString("kind")));
				tod.setType(Short.parseShort(detail.getString("type")));
				tod.setSerialNo(detail.getString("serialNo"));
				tod.setFactcode(detail.getString("factcode"));
				tod.setOtlcode(detail.getString("otlcode"));
				tod.setBatchid(detail.getInt("batchid"));
				tod.setAmount(detail.getLong("amount"));
				tod.setIn_price(detail.getDouble("in_price"));
				tod.setTax_money(detail.getDouble("tax_money"));
				tod.setPrice(detail.getDouble("price"));
				tod.setOut_price(detail.getDouble("out_price"));
				tod.setProd_date(new SimpleDateFormat("y-M-d").parse(detail.getString("prod_date")));
				tod.setRemark(detail.getString("remark"));
				System.out.println("=================================");
				System.out.println("单据ID 	:	" +tod.getNum());			
				System.out.println("物料名称 	:	" +tod.getMaterielName());			
				System.out.println("批号 	:	" +tod.getBatchno());			
				System.out.println("采购类型	:	" +tod.getKind());			
				System.out.println("入库类型 	:	" +tod.getType());			
				System.out.println("机身码 	:	" +tod.getSerialNo());			
				System.out.println("厂家条码 	:	" +tod.getFactcode());			
				System.out.println("OTL条码 	:	" +tod.getOtlcode());			
				System.out.println("批次 	:	" +tod.getBatchid());			
				System.out.println("入库数量 	:	" +tod.getAmount());			
				System.out.println("入库价格 	:	" +tod.getIn_price());			
				System.out.println("税额		:	" +tod.getTax_money());			
				System.out.println("零售价 	:	" +tod.getPrice());			
				System.out.println("批发价 	:	" +tod.getOut_price());			
				System.out.println("生产日期 	:	" +tod.getProd_date());			
				System.out.println("备注 	:	" +tod.getRemark());	
				boolean b = detail.has("ord");
				if(b){
					tod.setOrd(Integer.parseInt(detail.getString("ord")));
					k = getCcamsService().getTpoutdetailDao().updateTpoutdetail(tod);//执行更新
				}else{
					int ord = getCcamsService().getTpoutdetailDao().getNewOrd(numId);
					tod.setOrd(ord);
					k = getCcamsService().getTpoutdetailDao().insertTpoutdetail(tod);//执行添加	
				}
				if(k==1){
					TMaterielStock tms = new TMaterielStock();
//					tms.setMaterielName(tod.getMaterielName());
//					tms.setUname(toh.getUname());
					tms.setIdt_materiel(tod.getIdt_Materiel());
					tms.setUid(detail.getInt("uid"));
					int idt = getCcamsService().getTmaterielstockDao().getIdtStock(tms);
					if(idt==0){
						txm.rollback(status);
						jsonMap.put("success", "false");
						jsonMap.put("message", "部门库存中无此物料<"+tod.getMaterielName()+">的相关记录");
						json.putAll(jsonMap);
						return;
					}
					int stockAmount = getCcamsService().getTmaterielstockDao().getStockAmount(tms);//取得库存数量
					if(stockAmount < tod.getAmount()){//进行数量判断
						txm.rollback(status);
						jsonMap.put("success", "false");
						jsonMap.put("message", "物料<"+tod.getMaterielName()+">的库存不足");
						json.putAll(jsonMap);
						return;
					}
				}
			}
		}
		catch(Exception ex){
			txm.rollback(status);
	        ex.printStackTrace();
		}
		txm.commit(status);
		
		if (k == 1) {
			success = "true";
			message = "更新成功";
		} else {
			success = "false";
			message = "更新失败";
		}
		jsonMap.put("success", success);
		jsonMap.put("message", message);
		json.putAll(jsonMap);
	}
}
